﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace mp.message.util
{
    /// <summary>
    /// 请求校验工具类 
    /// </summary>
    public class SignUtil
    {
        // 与接口配置信息中的Token要一致  
        //private static String token = "taogonghuo";
        /// <summary>
        /// 验证签名 
        /// </summary>
        /// <param name="signature">微信加密签名  </param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <returns></returns>
        public static bool CheckSignature(String signature, String timestamp, String nonce)
        {
            try
            {
                string token = ConfigurationManager.AppSettings["token"];
                if (token == null)
                {
                    CommonFun.PrintLog("SignUtil:CheckSignature()", "请在web.config中配置<appSettings><add key='token' value=''/></appSettings>");
                    return false;
                }
                string[] ArrTmp = { token, timestamp, nonce };
                Array.Sort(ArrTmp);//字典排序
                string tmpStr = string.Join("", ArrTmp);
                tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");//对该字符串进行sha1加密
                tmpStr = tmpStr.ToLower();//对字符串中的字母部分进行小写转换，非字母字符不作处理
                if (tmpStr == signature)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                CommonFun.PrintExceptionLog(ex);
                return false;
            }
        }
    }
}
